import * as BABYLON from 'babylonjs';
import Snake from './objects/snake';
class Game{
    private _canvas:any;
    private _engine:BABYLON.Engine;
    private _scene:BABYLON.Scene;
    private _camera:BABYLON.Camera;
    private _light:BABYLON.Light;
    private _sk:Snake;
    private _dir:string = 'front';

    constructor(canvasID:string){
        this._canvas = document.getElementById(canvasID);
        this._engine = new BABYLON.Engine(this._canvas,true);
    }

    createScene():void{
        this._scene = new BABYLON.Scene(this._engine);
        this._camera = new BABYLON.FreeCamera('camera',new BABYLON.Vector3(0,20,-40),this._scene);
        this._camera.attachControl(this._canvas,false);
        this._light = new BABYLON.HemisphericLight('light',new BABYLON.Vector3(0,5,0),this._scene);

        let gdmt = new BABYLON.StandardMaterial('gdmt',this._scene);
        gdmt.diffuseTexture = new BABYLON.Texture('./resources/earth.jpg',this._scene);

        let ground = BABYLON.MeshBuilder.CreateGround('gr',
            {width:50,height:50,subdivisions:2},this._scene);
        ground.material = gdmt;

        this._sk = new Snake(this._scene,this._camera,new BABYLON.Vector2(0,0));
        this._camera.setTarget(this._sk.getPo());
    }

    doRender():void{
        this._engine.runRenderLoop(()=>{
            this._scene.render();
        });

        window.addEventListener('resize',()=>{
            this._engine.resize();
        });
    }

    turn(keyCode:number):void{
        this._sk.turn(keyCode);
    }

    start():void{
        this._sk.action();
        setInterval(()=>{
            this._camera.setTarget(this._sk.getPo());
        },this._sk.getUnitTime());
    }
}

window.addEventListener('DOMContentLoaded',()=>{
    let game = new Game('renderCanvas');
    game.createScene();
    game.doRender();
    game.start();

    document.body.onkeydown = (e)=>{
        game.turn(e.keyCode);
        console.log(e.keyCode);
    }

    document.getElementById('turnLt').onclick = ()=>{
        game.turn(65);
    }

    document.getElementById('turnRt').onclick = ()=>{
        game.turn(68);
    }
});